<?php

namespace app\api\Service;

use think\Db;
use think\Config;
use app\common\library\Auth;
use addons\epay\library\Service;

class ServiceExtraService
{
    // 列表
    public static function lists($data)
    {

        $list = \app\admin\model\ServiceExtra::where(['status'=>'normal'])->order('weigh desc')->field('id,title,price,duration')
            ->select();

        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    // 加钟
    public static function add($data)
    {
        try{
            $auth = Auth::instance();
            $order_id = $data['order_id'];
            $extra_id = $data['extra_id'];
            $user_id = $auth->id;

            if( !$order_id ){
                return ['code'=>0,'msg'=>'请选择要操作的订单','data'=>''];
            }
            if( !$user_id ){
                return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
            }

            //判断订单是否存在
            $order = \app\admin\model\Order::where('id', $order_id)->where('user_id', $user_id)->find();
            if (!$order) {
                return ['code' => 0, 'msg' => '订单信息不存在', 'data' => ''];
            }

            // 套餐信息是否存在
            $extra = \app\admin\model\ServiceExtra::where(['id'=>$extra_id])->find();
            if (!$extra) {
                return ['code' => 0, 'msg' => '加钟套餐不存在', 'data' => ''];
            }

            // 判断订单是否可以加钟
            if( $order['status'] != 4 && $order['status'] != 5 ) return ['code' => 0, 'msg' => '订单状态不可加钟', 'data' => ''];
            // 订单完场后超过10分钟也不可加钟
            if( $order['status'] == 5 && time() > ($order['dealtime'] + 600) ) return ['code' => 0, 'msg' => '订单完成时间已超过可加钟时间，请重新下单', 'data' =>
                ''];

            $params = [
                'order_id'  => $order_id,
                'user_id'  => $user_id,
                'steward_id'  => $order['steward_id'],
                'extra_id'  => $extra_id,
                'order_no'  => 'E'.getNewOrderNo(),
                'title'  =>  $extra['title'],
                'duration'  =>  $extra['duration'],
                'price'  =>  $extra['price'],
            ];

            $result = \app\admin\model\OrderExtra::create($params);

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
        if($result){
            return ['code'=>1,'msg'=>'操作成功','data'=>['id'=>$result['id']]];
        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }

    // 支付
    public static function pay($data)
    {
        $auth = Auth::instance();
        $id = $data['id'];
        $user_id = $auth->id;
        $user_id = 10;

        if( !$id ){
            return ['code'=>0,'msg'=>'请选择要支付的订单','data'=>''];
        }
        if( !$user_id ){
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
//        return $id;
        // 判断加钟订单是否存在
        $order = \app\admin\model\OrderExtra::where('id',$id)->where('user_id',$user_id)->find();

        if( !$order ){
            return ['code'=>0,'msg'=>'订单信息不存在','data'=>''];
        }
        if( $order['paid'] == 1 ){
            return ['code'=>0,'msg'=>'订单已支付','data'=>''];
        }

        if( !in_array($data['pay_type'],[1,2]) ) return ['code'=>0, 'msg'=>'请选择支付方式','data'=>''];

        //  判断加钟套餐是否存在
        $extra = \app\admin\model\ServiceExtra::where(['id'=>$order['extra_id']])->find();
        if (!$extra) {
            return ['code' => 0,'msg' => '加钟套餐不存在', 'data' => ''];
        }
        if($data['price'] != $extra['price']){
            return ['code'=>0, 'msg'=>'加钟套餐价格错误','data'=>''];
        }

        try{
            $params = [
                'pay_type'     => $data['pay_type'],
                'updatetime'     => time(),
            ];

            $result = \app\admin\model\OrderExtra::where(['id'=>$id])->where('user_id',$user_id)->update($params);

//            $result = true;

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

        if($result){

            $pay_type = ['1'=>'wechat','2'=>'alipay'];
            $type = $pay_type[$data['pay_type']];

            $params = [
                'amount'    => $data['price'],
                'orderid'   => $order['order_no'],
                'type'      => $type,
                'title'     => '【'.$extra['title'].'】',
                'method'    => 'app',
            ];
//            $params['amount'] = 0.01;// 测试支付
            $response = Service::submitOrder($params);

            if($data['pay_type'] == 1){
                $response = json_decode($response,true);
            }
            return ['code'=>1,'msg'=>'操作成功','data'=>$response];
            // 跳过支付
//            $ret = self::payResult(['out_trade_no' => $order['order_no'],'transaction_id' => $order['order_no']]);
//            return $ret;


        }else{
            return ['code'=>0,'msg'=>'操作失败','data'=>''];
        }
    }



    // 回调(测试用)
    public static function payResult($data)
    {
        //开启事务
        try{
            $order = \app\admin\model\OrderExtra::where('order_no', $data['out_trade_no'])->find();
            if(!$order){
                return false;
            }

            //判断是否已支付过
            if( $order->paid == 1 ){
                return false;
            }

            // 修改订单状态
            $order->trade_no = $data['trade_no'];
            $order->paid = 1;
            $order->paidtime = time();
            $order_result = $order->save();

            // 修改结束时间
            $overtime = time() + ($order->duration * 3600);
            $order_result = \app\admin\model\Order::where(['id'=>$order['order_id'],'user_id'=>$order['user_id']])
                ->update(['status'=>4,'overtime'=>$overtime,'updatetime'=>time()]);
            // 修改管家状态为服务中
            \app\admin\model\Steward::where(['id'=>$order->steward_id])->update(['service_status'=>2]);

            if( $order_result && $order_result ){
                DB::commit();
                return true;
            }else{
                DB::rollback();
                return false;
            }
        }catch(\Exception $e){
            DB::rollback();
            return $e->getMessage();
            return false;
        }
    }
}